package com.itxh.factory;

import com.itxh.model.BeanDefinition;
import com.itxh.registry.BeanDefinitionRegistry;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DefaultListableBeanFactory extends AbstractAutowireCapableBeanFactory implements ListableBeanFactory, BeanDefinitionRegistry {
    // 用来存储配置文件中bean标签的信息（bean的原材料信息）
    private Map<String, BeanDefinition> beanDefinitions = new HashMap<>();

    private List<BeanDefinition> beanDefinitionList = new ArrayList<>();

    @Override
    public void registerBeanDefinition(String beanName, BeanDefinition bd) {
        this.beanDefinitions.put(beanName,bd);
    }

    @Override
    public BeanDefinition getBeanDefinition(String name) {
        return this.beanDefinitions.get(name);
    }

    @Override
    public List<BeanDefinition> getBeanDefinitions() {
        if (beanDefinitionList == null || beanDefinitionList.size() == 0){
            for(BeanDefinition bd : beanDefinitions.values()){
                beanDefinitionList.add(bd);
            }
        }
        return beanDefinitionList;
    }

    @Override
    public <T> List<T> getBeansByType(Class type) {
        List<T> beans = new ArrayList<>();
        List<BeanDefinition> bdList = getBeanDefinitions();
        for (BeanDefinition bd : bdList) {
            if(type.isAssignableFrom(bd.getClazzType())){
                beans.add((T) getBean(bd.getId()));
            }
        }
        return beans;
    }
}
